<template>
  <div class="model-form">
    <el-dialog v-model="dialogFormVisible" :title="props.dialogTitle" :before-close="handleClose" :fullscreen="true"
      draggable align-center>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="dialogRules">
        <el-form-item label="所属图谱" :label-width="formLabelWidth" prop="graphName">
          <el-input v-model="ruleForm.graphName" placeholder="请输入所属图谱" :disabled="true" clearable />
        </el-form-item>
        <el-form-item label="所属图谱ID" :label-width="formLabelWidth" prop="graphId">
          <el-input v-model="ruleForm.graphId" placeholder="请输入所属图谱ID" :disabled="true" clearable />
        </el-form-item>
        <el-form-item label="实体类型" :label-width="formLabelWidth" prop="entityType">
          <el-select v-model="ruleForm.entityType" style="width: 100%" placeholder="请选择实体类型" clearable>
            <el-option label="人物图谱" value="1" />
            <el-option label="事件图谱" value="2" />
<!--            <el-option label="地点图谱" value="3" />
            <el-option label="时间图谱" value="4" />-->
          </el-select>
        </el-form-item>
        <div v-if="ruleForm.entityType === '1'">
          <el-form-item label="实体名称" :label-width="formLabelWidth" prop="entityName">
            <el-input v-model="ruleForm.entityName" placeholder="请输入实体名称" clearable />
          </el-form-item>
          <el-form-item label="别名" :label-width="formLabelWidth" prop="anotherName">
            <el-input v-model="ruleForm.anotherName" placeholder="请输入别名" clearable />
          </el-form-item>
          <el-form-item label="国籍" :label-width="formLabelWidth" prop="country">
            <el-input v-model="ruleForm.country" placeholder="请输入实体国籍" clearable />
          </el-form-item>
          <el-form-item label="民族" :label-width="formLabelWidth" prop="nation">
            <el-input v-model="ruleForm.nation" placeholder="请输入实体民族" clearable />
          </el-form-item>
          <el-form-item label="出生地" :label-width="formLabelWidth" prop="placeOfBirth">
            <el-input v-model="ruleForm.placeOfBirth" placeholder="请输入实体出生地" clearable />
          </el-form-item>
          <el-form-item label="出生日期" :label-width="formLabelWidth" prop="birthday">
            <el-input v-model="ruleForm.birthday" placeholder="请输入实体出生日期" clearable />
          </el-form-item>
          <el-form-item label="死亡日期" :label-width="formLabelWidth" prop="deathDay">
            <el-input v-model="ruleForm.deathDay" placeholder="请输入实体死亡日期" clearable />
          </el-form-item>
          <el-form-item label="工作职责" :label-width="formLabelWidth" prop="job">
            <el-input v-model="ruleForm.job" placeholder="请输入实体工作职责" clearable />
          </el-form-item>
          <el-form-item label="毕业院校" :label-width="formLabelWidth" prop="graduate">
            <el-input v-model="ruleForm.graduate" placeholder="请输入实体毕业院校" clearable />
          </el-form-item>
          <el-form-item label="作品" :label-width="formLabelWidth" prop="works">
            <el-input v-model="ruleForm.works" placeholder="请输入实体作品" clearable />
          </el-form-item>
          <el-form-item label="实体简介" :label-width="formLabelWidth" prop="entityIntro">
            <!-- <el-input v-model="ruleForm.entityIntro" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }"
              resize="none" placeholder="请输入实体简介" /> -->
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef1" :defaultConfig="toolbarConfig1"
                :mode="mode1" />
              <Editor style="height: 100px; overflow-y: hidden;" v-model="ruleForm.entityIntro"
                :defaultConfig="editorConfig1" :mode="mode1" @onCreated="handleCreated1" />
            </div>
          </el-form-item>
          <el-form-item label="实体经历" :label-width="formLabelWidth" prop="entityExperience">
            <!-- <el-input v-model="ruleForm.entityExperience" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }"
              resize="none" placeholder="请输入实体经历" /> -->
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef2" :defaultConfig="toolbarConfig2"
                :mode="mode2" />
              <Editor style="height: 300px; overflow-y: hidden;" v-model="ruleForm.entityExperience"
                :defaultConfig="editorConfig2" :mode="mode2" @onCreated="handleCreated2" />
            </div>
          </el-form-item>
          <el-form-item label="实体图片" :label-width="formLabelWidth" prop="entityPhotoUrl">
            <el-upload :http-request="uploadPhoto" class="avatar-uploader" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" style="width: 178px" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <div v-if="ruleForm.entityType === '2'">
<!--          <el-form-item label="事件来源句子" :label-width="formLabelWidth" prop="sentence">
            <el-input v-model="ruleForm.sentence" placeholder="请输入事件来源句子" clearable />
          </el-form-item>-->
          <el-form-item label="事件名" :label-width="formLabelWidth" prop="eventName">
            <el-input v-model="ruleForm.desc" type="textarea" :autosize="{ minRows: 3, maxRows: 3 }" resize="none"
                      placeholder="请输入事件名" />
          </el-form-item>
          <el-form-item label="事件描述" :label-width="formLabelWidth" prop="desc">
            <el-input v-model="ruleForm.desc" type="textarea" :autosize="{ minRows: 3, maxRows: 3 }" resize="none"
              placeholder="请输入事件描述" />
          </el-form-item>
<!--          <el-form-item label="事件相关人物" :label-width="formLabelWidth" prop="persons">
            <el-input v-model="ruleForm.persons" placeholder="请输入事件相关人物" clearable />
          </el-form-item>
          <el-form-item label="事件相关机构" :label-width="formLabelWidth" prop="orgs">
            <el-input v-model="ruleForm.orgs" clearable placeholder="请输入事件相关机构" />
          </el-form-item>-->
<!--          <el-form-item label="事件动词描述" :label-width="formLabelWidth" prop="verbDescription">
            <el-input v-model="ruleForm.verbDescription" placeholder="请输入事件动词描述" clearable />
          </el-form-item>
          <el-form-item label="事件动词" :label-width="formLabelWidth" prop="eventVerb">
            <el-input v-model="ruleForm.eventVerb" placeholder="请输入事件动词" clearable />
          </el-form-item>-->
          <el-form-item label="事件发生时间" :label-width="formLabelWidth" prop="eventDate">
            <el-date-picker v-model="ruleForm.eventDate" type="date" placeholder="请输入事件发生时间" size="default" />
          </el-form-item>
          <el-form-item label="事件发生地点" :label-width="formLabelWidth" prop="eventLocation">
            <el-input v-model="ruleForm.eventLocation" placeholder="请输入事件发生地点" clearable />
          </el-form-item>
          <el-form-item label="事件详情" :label-width="formLabelWidth" prop="eventDetails">
            <!-- <el-input v-model="ruleForm.entityExperience" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }"
              resize="none" placeholder="请输入实体经历" /> -->
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef2" :defaultConfig="toolbarConfig2"
                       :mode="mode2" />
              <Editor style="height: 300px; overflow-y: hidden;" v-model="ruleForm.eventDetails"
                      :defaultConfig="editorConfig2" :mode="mode2" @onCreated="handleCreated2" />
            </div>
          </el-form-item>
<!--          <el-form-item label="受事者" :label-width="formLabelWidth" prop="recipient">
            <el-input v-model="ruleForm.recipient" placeholder="请输入受事者" clearable />
          </el-form-item>
          <el-form-item label="施事者" :label-width="formLabelWidth" prop="agent">
            <el-input v-model="ruleForm.agent" placeholder="请输入施事者" clearable />
          </el-form-item>-->
        </div>
        <div v-if="ruleForm.entityType === '3'">
          <el-form-item label="地点" :label-width="formLabelWidth" prop="place">
            <el-input v-model="ruleForm.place" type="textarea" :autosize="{ minRows: 3, maxRows: 3 }" resize="none"
              placeholder="请输入地点" />
          </el-form-item>
        </div>
        <div v-if="ruleForm.entityType === '4'">
          <el-form-item label="事件发生时间" :label-width="formLabelWidth" prop="occurrenceTime">
            <el-date-picker v-model="ruleForm.occurrenceTime" type="date" placeholder="请输入事件发生时间" size="default" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          <el-button @click="Cancel(ruleFormRef)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="tsx" setup>
import * as FormApi from '@/api/knowledge/character'
import { ElMessage, UploadRequestOptions } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// components: { Editor, Toolbar },
// 编辑器实例，必须用 shallowRef
const editorRef1 = shallowRef()
const editorRef2 = shallowRef()
// 内容 HTML
const valueHtml = ref('<p>hello</p>')
// 模拟 ajax 异步获取内容
onMounted(() => {
  console.log(dialogFormVisible.value)
  setTimeout(() => {
    // valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    valueHtml.value = dialogFormVisible.value.entityIntro
  }, 1500)
})
const mode1 = 'default' // 或 'simple'
const mode2 = 'default' // 或 'simple'
const toolbarConfig1 = {}
const toolbarConfig2 = {}
const editorConfig1 = { placeholder: '请输入内容...' }
const editorConfig2 = { placeholder: '请输入内容...' }

const handleClose = (done: () => void) => {
  Object.keys(ruleForm).map(item => ruleForm[item] = '')
  ruleForm.graphName = String(route.query.graphName)
  ruleForm.graphId = String(route.query.graphId)
  done()
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor1 = editorRef1.value
  if (editor1 == null) return
  editor1.destroy()
  const editor2 = editorRef2.value
  if (editor2 == null) return
  editor2.destroy()
})

const handleCreated1 = (editor) => {
  editorRef1.value = editor // 记录 editor 实例，重要！
}
const handleCreated2 = (editor) => {
  editorRef2.value = editor // 记录 editor 实例，重要！
}

const router = useRouter()
const route = useRoute()
const props = defineProps({
  dialogTitle: String
})
const emits = defineEmits(['subEvent'])
const ruleFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const formLabelWidth = '100px'
interface RuleForm {
  graphName: string
  graphId: string
  entityName: string
  anotherName: string
  country: string
  nation: string
  placeOfBirth: string
  deathDay: string
  birthday: string
  job: string
  graduate: string
  works: string
  entityIntro: string
  entityExperience: string
  entityType: string
  entityPhotoUrl: any
}
const ruleForm = reactive({
  graphName: String(route.query.graphName),
  graphId: String(route.query.graphId),
  entityName: '',
  anotherName: '',
  country: '',
  nation: '',
  placeOfBirth: '',
  deathDay: '',
  birthday: '',
  job: '',
  graduate: '',
  works: '',
  entityIntro: '',
  entityExperience: '',
  entityType: '',
  entityPhotoUrl: '',
  id: ''
})
const dialogRules = reactive<FormRules<RuleForm>>({
  graphName: [{ required: true, message: '请输入所属图谱', trigger: 'change' }],
  graphId: [{ required: true, message: '请输入所属图谱ID', trigger: 'change' }],
  entityName: [{ required: true, message: '请输入实体名称', trigger: 'change' }],
  entityIntro: [{ required: true, message: '请输入实体简介', trigger: 'change' }],
  entityExperience: [{ required: true, message: '请输入实体经历', trigger: 'change' }],
  entityType: [{ required: true, message: '请选择实体类型', trigger: 'change' }]
})
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}
let excelFormData = new FormData()
// 文件上传
const uploadPhoto = async (param: UploadRequestOptions) => {
  excelFormData = new FormData()
  excelFormData.append('entityPhotoFile', param.file)
}
// 打开弹窗状态（新增或编辑）
const handleTypeProps = ref<string>('')
const open = async (data: any, handleType: string) => {
  console.log(data.rowData)
  if (handleType === 'add') imageUrl.value = ''
  if (handleType === 'edit') {
    data.rowData.entityType = String(data.rowData.entityType)
    Object.assign(ruleForm, data.rowData)
    imageUrl.value = data.rowData.entityPhotoUrl
  }
  handleTypeProps.value = handleType
  dialogFormVisible.value = true
}
defineExpose({ open })
// 弹窗取消
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  Object.keys(ruleForm).forEach((key) => (ruleForm[key] = ''))
  ruleForm.graphName = String(route.query.graphName)
  ruleForm.graphId = String(route.query.graphId)
  dialogFormVisible.value = false
}
// 弹窗确定
const submitForm = async (formEl: FormInstance | undefined) => {
  excelFormData.append('graphName', ruleForm.graphName)
  excelFormData.append('anotherName', ruleForm.anotherName!==null?ruleForm.anotherName:"");
  excelFormData.append('country', ruleForm.country!==null?ruleForm.country:"")
  excelFormData.append('nation', ruleForm.nation!==null?ruleForm.nation:"")
  excelFormData.append('placeOfBirth', ruleForm.placeOfBirth!==null?ruleForm.placeOfBirth:"")
  excelFormData.append('deathDay', ruleForm.deathDay!==null?ruleForm.deathDay:"")
  excelFormData.append('birthday', ruleForm.birthday!==null?ruleForm.birthday:"")
  excelFormData.append('job', ruleForm.job!==null?ruleForm.job:"")
  excelFormData.append('graduate', ruleForm.graduate!==null?ruleForm.graduate:"")
  excelFormData.append('works', ruleForm.works!==null?ruleForm.works:"")
  excelFormData.append('graphId', ruleForm.graphId)
  excelFormData.append('entityName', ruleForm.entityName)
  excelFormData.append('entityIntro', ruleForm.entityIntro)
  excelFormData.append('entityExperience', ruleForm.entityExperience)
  excelFormData.append('entityType', ruleForm.entityType)
  excelFormData.append('id', ruleForm.id)
  const params = excelFormData
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.entityType === '1') {
        if (handleTypeProps.value === 'add') {
          FormApi.insertHybaseGraphEntity(params).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            Object.keys(ruleForm).forEach((key) => (ruleForm[key] = ''))
            ruleForm.graphName = String(route.query.graphName)
            ruleForm.graphId = String(route.query.graphId)
            ElMessage({
              message: '添加成功',
              showClose: true,
              type: 'success'
            })
            console.log('ruleForm.entityType2', ruleForm.entityType)
            emits('subEvent', ruleForm.entityType)
          })
        } else if (handleTypeProps.value === 'edit') {
          FormApi.updateHybaseGraphEntity(params).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            ElMessage({
              message: '修改成功',
              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        }
      }
      else if (ruleForm.entityType === '2') {
        console.log(ruleForm.entityType)
        const params2 = ruleForm
        params2.eventDate = dayjs(params2.eventDate).format('YYYY/MM/DD HH:mm:ss')
        if (handleTypeProps.value === 'add') {
          FormApi.insertHybaseGraphEvent(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            Object.keys(ruleForm).forEach((key) => (ruleForm[key] = ''))
            ruleForm.graphName = String(route.query.graphName)
            ruleForm.graphId = String(route.query.graphId)
            ElMessage({
              message: '添加成功',

              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        } else if (handleTypeProps.value === 'edit') {
          FormApi.updateHybaseGraphEvent(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            ElMessage({
              message: '修改成功',

              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        }
      }
      else if (ruleForm.entityType === '3') {
        console.log(ruleForm.entityType)
        const params2 = ruleForm
        if (handleTypeProps.value === 'add') {
          FormApi.insertHybaseGraphPlace(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            Object.keys(ruleForm).forEach((key) => (ruleForm[key] = ''))
            ruleForm.graphName = String(route.query.graphName)
            ruleForm.graphId = String(route.query.graphId)
            ElMessage({
              message: '添加成功',
              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        } else if (handleTypeProps.value === 'edit') {
          FormApi.updateHybaseGraphPlace(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            ElMessage({
              message: '修改成功',
              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        }
      }
      else if (ruleForm.entityType === '4') {
        console.log(ruleForm.entityType)
        const params2 = ruleForm
        params2.occurrenceTime = dayjs(params2.occurrenceTime).format('YYYY/MM/DD HH:mm:ss')
        params2.year = dayjs(params2.occurrenceTime).format('YYYY')
        params2.month = dayjs(params2.occurrenceTime).format('MM')
        params2.day = dayjs(params2.occurrenceTime).format('DD')
        if (handleTypeProps.value === 'add') {
          FormApi.insertHybaseGraphTime(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            Object.keys(ruleForm).forEach((key) => (ruleForm[key] = ''))
            ruleForm.graphName = String(route.query.graphName)
            ruleForm.graphId = String(route.query.graphId)
            ElMessage({
              message: '添加成功',

              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        } else if (handleTypeProps.value === 'edit') {
          FormApi.updateHybaseGraphTime(params2).then((res) => {
            console.log(res)
            dialogFormVisible.value = false
            formEl.resetFields()
            excelFormData = new FormData()
            ElMessage({
              message: '修改成功',

              showClose: true,
              type: 'success'
            })
            emits('subEvent', ruleForm.entityType)
          })
        }
      }
    } else console.log('error submit!', fields)
  })
}
</script>
<style lang="scss" scoped>
.model-form {

  // 图片上传样式
  ::v-deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  ::v-dee(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}

::v-deep(.el-dialog) {
  // margin: 0;
}
</style>
